﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static LightCAD.MathLib.Constants;
using LightCAD.Three.OpenGL;

namespace LightCAD.Three
{
    public static class WebGLShaderUtils
    {
        public static string addLineNumbers(string str)
        {


            var lines = str.Split('\n');

            for (var i = 0; i < lines.Length; i++)
            {

                lines[i] = (i + 1) + ": " + lines[i];

            }

            return string.Join("\n", lines);

        }

        public static Func<int, string, int> WebGLShader = (type, str) =>
        {

            var shader = gl.createShader(type);

            //由于C#的string.Length不是字符串Byte长度，可能发生'pre-mature EOF'错误,所以加空串在后面避免错误
            str += new string(' ', 1024);
            gl.shaderSource(shader, str);
            gl.compileShader(shader);

            if (gl.getShaderParameter(shader, gl.COMPILE_STATUS) == 0)
            {

                console.error("THREE.WebGLShader = Shader couldn\'t compile.");

            }

            if (gl.getShaderInfoLog(shader) != "")
            {

                console.warn("THREE.WebGLShader = gl.getShaderInfoLog()", type == gl.VERTEX_SHADER ? "vertex" : "fragment", gl.getShaderInfoLog(shader), addLineNumbers(str));

            }

            // --enable-privileged-webgl-extension
            // console.log( type, gl.getExtension( "WEBGL_debug_shaders" ).getTranslatedShaderSource( shader ) );

            return shader;

        };
    }
}
